<?php

/**
 * Created by PhpStorm.
 * User: songshuai
 * Date: 2019/7/16
 * Time: 15:52
 */

namespace App\Jobs;

use http\Exception\BadMessageException;
use Illuminate\Support\Facades\DB;
use App\admin\Service\OA;

class Fun
{

    const ERROR_SHOW = 1;

    const app_access='qSoiKwpWVge4TkaryH6MKvOdceGt7ZMaF20g8H0cnXI';

    public static function date($time = 0, $showtime = true)
    {
        if (empty($time))
            return '';
        if ($showtime) {
            return date("Y-m-d H:i:s", $time);
        } else {
            return date("Y-m-d", $time);
        }

    }

    public static function encode($content, $doubleEncode = true)
    {
        return htmlspecialchars($content, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8', $doubleEncode);
    }

    /**
     * 校验日期格式是否正确
     *
     * @param string $date 日期
     * @param string $formats 需要检验的格式数组
     * @return boolean
     */
    public static function checkDateIsValid($date, $formats = array("Y-m-d", "Y/m/d"))
    {
        $unixTime = strtotime($date);
        if (!$unixTime) { //strtotime转换不对，日期格式显然不对。
            return false;
        }
        //校验日期的有效性，只要满足其中一个格式就OK
        foreach ($formats as $format) {
            if (date($format, $unixTime) == $date) {
                return true;
            }
        }

        return false;
    }


    public static function showmsg($msg, $type = self::ERROR_SHOW)
    {
        if (self::isAjax()) {
            OA::Json(1, $msg);
        }
        echo "<h1>" . $msg . "</h1>"; exit;
        //   throw new BadMessageException($msg);
       //
    }


    public static function isAjax()
    {
        return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
    }

    /**@var
     * 网站域名
     */
    public static $HOST = 'http://www.fuzhuangchangongxiao.cn';

    /**
     * 网站默认图片
     */
    public static $Pic = '/h5/images/logo-di.png';


    /**
     * 转换图片链接
     */
    public static function pImg($src)
    {
        if (empty($src)) {
            return self::$HOST . self::$Pic;
        }
        if ($src[0] === '/') {
            $src = self::$HOST . $src;
        }
        return $src;
    }


    /**
     * 获取ip地址
     */
    public static function Ip()
    {
        if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))
            $ip = getenv("HTTP_CLIENT_IP");
        else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown"))
            $ip = getenv("HTTP_X_FORWARDED_FOR");
        else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
            $ip = getenv("REMOTE_ADDR");
        else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
            $ip = $_SERVER['REMOTE_ADDR'];
        else
            $ip = "";

        if (empty($ip))
            return Yii::$app->request->userIP;

        $albumlist = explode(",", $ip);
        return $albumlist[0];
    }


    /**
     * 判断是否为手机版
     */
    public static function UA()
    {
        if (!isset($_SERVER['HTTP_USER_AGENT'])) {
            return '';
        } else {
            return $_SERVER['HTTP_USER_AGENT'];
        }
    }


    /**
     * 跳转到登录
     */
    public static function goLogin()
    {
        if (self::isAjax()) {
            OA::Json(OA::Guest);
            return null;
        } else {
            return redirect('/h5/login/login.html');
        }
    }


    /**
     * Curl版本
     * 使用方法：
     * $post_string = "app=request&version=beta";
     * request_by_curl('http://facebook.cn/restServer.php',$post_string);
     */
    public static function request_by_curl($remote_server, $post_string=[])
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $remote_server);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_string));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_USERAGENT, "");
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/x-www-form-urlencoded']);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }


    public static function curl_get($url) {
       /// echo "ff\r\n";
        $cookies='__c=1586585832; __g=-; __l=l=%252Fjob_detail%252Fd05eb4fbc451e2271XF42dW4F1Q%257E.html%253Fka%253Djob_list_1_blank%2526lid%253Dnlp-1wAriciIeJr.search.1&r=https%253A%252F%252Fwww.zhipin.com%252Fweb%252Fcommon%252Fsecurity-check.html%253Fseed%253DS8nC%25252BsdfWpFUzsQYrjz1Kp81VqG6zz7PevhWGpvRogA%25253D%2526name%253Dd75ecf73%2526ts%253D1586584680934%2526callbackUrl%253D%25252Fjob_detail%25252Fd05eb4fbc451e2271XF42dW4F1Q%25257E.html%25253Fka%25253Djob_list_1_blank%252526lid%25253Dnlp-1wAriciIeJr.search.1%2526srcReferer%253Dhttps%25253A%25252F%25252Fwww.zhipin.com%25252Fjob_detail%25252F%25253Fka%25253Dheader-job&friend_source=0&friend_source=0; Hm_lvt_194df3105ad7148dcf2b98a91b5e727a=1586574512,1586577337; __a=62483598.1586585832..1586585832.4.1.4.4; __zp_stoken__=f9f4Ztlum6bO0wj48TKzDu3VzgZd3qORNCjHQ0GPzId9%2ByaavwJxqrwijThDx37CAl5RErr8XfqD5m%2BMTU0iVbunCnynp21G2hBQvvrobInkiR1WG92S9OQe6x%2FBGiK44qQw; Hm_lpvt_194df3105ad7148dcf2b98a91b5e727a=1586586390';


        $ch = curl_init();

		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36");
        curl_setopt($ch, CURLOPT_REFERER, "http://www.163.com");
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_COOKIE, $cookies);

        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_NOSIGNAL,1);    //注意，毫秒超时一定要设置这个
        curl_setopt($ch, CURLOPT_TIMEOUT_MS,5000);  //超时毫秒，cURL 7.16.2中被加入。从PHP 5.2.3起可使用

        // echo "ff116\r\n";
        $data = curl_exec($ch);
       //  echo "118\r\n";

        curl_close($ch);
        return $data;
    }

    /**
     * 判断是否为手机版
     */
    public static function isMobile()
    {
        // if(Fun::isDebug()){         return true;        }
        $mobilebrowser_list = array('iphone', 'android', 'phone', 'mobile', 'wap', 'netfront', 'java', 'opera mobi', 'opera mini',
            'ucweb', 'windows ce', 'symbian', 'series', 'webos', 'sony', 'blackberry', 'dopod', 'nokia', 'samsung',
            'palmsource', 'xda', 'pieplus', 'meizu', 'midp', 'cldc', 'motorola', 'foma', 'docomo', 'up.browser',
            'up.link', 'blazer', 'helio', 'hosin', 'huawei', 'novarra', 'coolpad', 'webos', 'techfaith', 'palmsource',
            'alcatel', 'amoi', 'ktouch', 'nexian', 'ericsson', 'philips', 'sagem', 'wellcom', 'bunjalloo', 'maui', 'smartphone',
            'iemobile', 'spice', 'bird', 'zte-', 'longcos', 'pantech', 'gionee', 'portalmmm', 'jig browser', 'hiptop',
            'benq', 'haier', '^lct', '320x320', '240x320', '176x220', 'pad', 'gt-p1000');
        if (!isset($_SERVER['HTTP_USER_AGENT'])) return false;
        $useragent = strtolower($_SERVER['HTTP_USER_AGENT']);
        if ((self::dstrpos($useragent, $mobilebrowser_list))) {
            return true;
        }

        return false;
    }

    public static function dstrpos($string, &$arr)
    {
        if (empty($string))
            return false;
        foreach ((array)$arr as $v) {
            if (strpos($string, $v) !== false) {
                return $v;
            }
        }
        return false;
    }


    public static function shenglue($str_cut, $length = 32)
    {
        if (mb_strlen($str_cut, 'utf-8') > $length) {

            $str_cut = mb_substr($str_cut, 0, $length, 'utf-8') . '…'; //截取头5个字，假定此代码所在php文件的编码为utf-8
        }

        return $str_cut;
    }


    /**
     * 计算两个坐标的距离
     * @param lng1 $ ,lng2 经度
     * @param lat1 $ ,lat2 纬度
     * @return float 距离，单位米
     */
    public static function getdistance($lng1, $lat1, $lng2, $lat2)
    {
        // 将角度转为狐度
        $radLat1 = deg2rad($lat1); //deg2rad()函数将角度转换为弧度
        $radLat2 = deg2rad($lat2);
        $radLng1 = deg2rad($lng1);
        $radLng2 = deg2rad($lng2);
        $a = $radLat1 - $radLat2;
        $b = $radLng1 - $radLng2;
        $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2))) * 6378.137 * 1000;
        return $s;

    }




     /**
     * 把数据的对象格式转换成数据格式
     * @param $object
     * @return mixed
     */
    public static function objToArr($obj)
    {
        if (is_string($obj)) {
            $obj = json_decode($obj);
        }
        $arr = array();
     ///   var_dump($obj);exit;
        if(empty($obj)){
            return $arr;
        }
        foreach($obj as $k=>$v) {
            if(is_object($v) || is_array($v)) {
                $arr[$k] = self::objToArr($v);
            } else {
                $arr[$k] = $v ? $v : '';
            }
        }
        return $arr;
    }





}
